package com.design3.graduatethesissys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.design3.graduatethesissys.common.utils.UUIDUtils;
import com.design3.graduatethesissys.domain.Message;
import com.design3.graduatethesissys.domain.SysUser;
import com.design3.graduatethesissys.service.impl.MessageServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class MessageController {
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    MessageServiceImpl messageService;
    @MessageMapping("/chat")
    public Message greeting(Authentication authentication,Message message) throws Exception {
        Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(authentication.getPrincipal()));
        String form = (String) map.get("username");
        SysUser sysUser = messageService.findMessageById(message.getTo_id());
        //完善message信息
        message.setFrom_id(form);
        CompletMessage(message);
        message.setFrom_name((String) map.get("name"));
        message.setTo_name(sysUser.getName());
        message.setMes_status("zt01");//默认未读状态

        //这里更新所有的旧的相关消息，设置为已读
        messageService.updateOldMessage(message.getFrom_id(),message.getTo_id());
        //保存message
        messageService.insertMessage(message);

//        List<Message> messages = messageService.getNewMessageById(message.getFrom_id(),message.getTo_id());

        //拼接转发URL
        String jsonString_from = "{name="+map.get("name")+", username="+map.get("username")+"}";
        simpMessagingTemplate.convertAndSendToUser(jsonString_from,"/queue/chat",message);
        String jsonString_to = "{name="+sysUser.getName()+", username="+sysUser.getUsername()+"}";
        simpMessagingTemplate.convertAndSendToUser(jsonString_to,"/queue/chat",message);
        return message;
    }
    public void CompletMessage(Message message){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        message.setDate(df.format(new Date()));
        message.setMes_id(UUIDUtils.getUUID());
    }
}
